package com.example.tool.util;

import com.alibaba.fastjson.JSONObject;
import com.example.tool.bean.weather.WeatherHistoryGetResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class WeatherUtil {

    // id密钥
    private static final String appId = "39439373";
    private static final String appSecret = "qNCYn2wP";
    // 历史天气接口
    private static final String historyWeatherUrl = "http://gfeljm.tianqiapi.com/free/history?appid=%s&appsecret=%s&cityid=%s&year=%s&month=%s&date=%s";

    /**
     * 获取天气API历史天气
     */
    public static WeatherHistoryGetResponse queryHistoryWeather(String cityId, String year, String month, String startDate, String endDate) {
        if (StringUtils.isBlank(cityId)) {
            throw new RuntimeException("城市ID不能为空");
        }
        String date = "";
        if (StringUtils.isNotBlank(startDate) || StringUtils.isNotBlank(endDate)) {
            if (StringUtils.isBlank(startDate)) {
                date = startDate;
            } else if (StringUtils.isBlank(endDate)) {
                date = endDate;
            } else {
                date = startDate + "_" + endDate;
            }
            year = "";
            month = "";
        } else if (StringUtils.isNotBlank(year) || StringUtils.isNotBlank(month)) {
            if (StringUtils.isBlank(year)) {
                throw new RuntimeException("请选择查询年份");
            }
            date = "";
        }
        if (StringUtils.isBlank(year) && StringUtils.isBlank(month) && StringUtils.isBlank(date)) {
            throw new RuntimeException("查询时间不能为空");
        }
        String url = java.lang.String.format(historyWeatherUrl, appId, appSecret, cityId, year, month, date);
        log.info("查询历史天气调用:{}", url);
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpGet httpGet = new HttpGet(url);
            try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
                String responseBody = EntityUtils.toString(response.getEntity());
                log.info("查询历史天气结果返回:{}", responseBody);
                return JSONObject.parseObject(responseBody, WeatherHistoryGetResponse.class);
            }
        } catch (Exception e) {
            log.error("查询历史天气异常:", e);
            throw new RuntimeException(e);
        }
    }

}
